package com.rgs.base.tasks.excel;

import com.google.common.io.Files;
import com.rgs.base.core.file.storage.FileStorageService;
import com.rgs.base.core.function.CheckFunction;
import com.rgs.base.core.page.IPageRequestModel;
import com.rgs.base.core.page.IPageResponseModel;
import com.rgs.base.core.statics.CommonParamStaticClass;
import com.rgs.base.core.util.FileNameUtil;
import com.rgs.base.core.util.excel.ExcelUtil;
import com.rgs.base.core.util.excel.ExcelWriteIterator;
import com.rgs.base.core.util.excel.bo.ExcelConfigBO;
import com.rgs.base.tasks.task.AsyncTaskHandle;
import com.rgs.base.tasks.task.AsyncTaskRunnableBO;

import java.io.File;
import java.time.LocalDate;
import java.util.List;

/**
 * @author Ren Gaoshuai
 * @date 2022-03-08 15:45
 **/
public abstract class AbstractExportExcelHandle<T> implements AsyncTaskHandle {
    /**
     * 获取泛型的class
     *
     * @return java.lang.Class<T>
     * @author daxiong
     * @date 2020/8/21 1:40 下午
     */
    public abstract Class<T> getDestClass();

    public abstract IPageRequestModel getPageRequestModel();

    public abstract FileStorageService getFileStorageService();

    public abstract CheckFunction<IPageRequestModel, IPageResponseModel> getReadNextPage();

    /**
     * 获取导出配置文件
     *
     * @return
     */
    public abstract ExcelConfigBO getExcelConfigBO();

    /**
     * 合计数据，没有则为null
     *
     * @param
     * @return List<T>
     * @author daxiong
     * @date 2020/12/28 上午11:13
     */
    public abstract List<T> getTotal();

    @Override
    public AsyncTaskRunnableBO execute(AsyncTaskRunnableBO asyncTaskRunnable) throws Exception {

        ExcelWriteIterator<T> excelWriteIterator = new ExcelWriteIterator<T>(
                this.getPageRequestModel(), this.getReadNextPage()
        );
        String fileUuid = FileNameUtil.generateNameFile(CommonParamStaticClass.OFFICE_EXCEL_XLSX);
        File tempDir = Files.createTempDir();
        File file = new File(tempDir, fileUuid);
        try {

            ExcelUtil.writeExcel(file,
                    excelWriteIterator,
                    this.getDestClass(),
                    this.getExcelConfigBO(),
                    this.getTotal());
            //
            this.getFileStorageService().saveForInputStream(
                    Files.asByteSource(file).openBufferedStream(),
                    fileUuid);
            asyncTaskRunnable.setFileName(fileUuid);
            asyncTaskRunnable.setFileUrl(
                    this.getFileStorageService().fileUrl(fileUuid,
                            this.getExcelConfigBO().getExportTitle(),
                            LocalDate.now()));
            return asyncTaskRunnable;
        } finally {
            tempDir.delete();
        }

    }

}
